package com.chen.base.module.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chen.base.inter.CurrUserInter;
import com.chen.base.utils.SpringContextHolder;
import com.chen.base.utils.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;

import java.time.LocalDateTime;

/**
 * 自动填充
 * @author ~龙~
 */
@Slf4j
public class DefaultMetaObjectHandler implements MetaObjectHandler {

    @Value("${mybatis-plus.global-config.db-config.logic-not-delete-value:0}")
    private String notDeleteValue;

    @Override
    public void insertFill(MetaObject metaObject) {
        CurrUserInter currUserInter = SpringContextHolder.getBean(CurrUserInter.class);
        this.strictInsertFill(metaObject, "tenantId", String.class, TenantContextHolder.getTenantId());
        this.strictInsertFill(metaObject, "delFlag", String.class, notDeleteValue);
        this.strictInsertFill(metaObject, "revision", Integer.class, 0);
        this.strictInsertFill(metaObject, "createBy", String.class, currUserInter.currUserId());
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 问题: 属性只有为null才会填充，所以修改一下
        if(metaObject.hasSetter("updateBy")){
            metaObject.setValue("updateBy", null);
        }
        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", null);
        }
        CurrUserInter currUserInter = SpringContextHolder.getBean(CurrUserInter.class);
        this.strictUpdateFill(metaObject, "updateBy", String.class, currUserInter.currUserId());
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }


}